'use strict'

var ARC_SIZE = 20;
var NODE_SIZE = 40;
var DEFAULT_ID = '110';

function Chord(){
	this.dept = {};
	this.depts = {};

	this.arcs = [];
	this.nodes = [];
	this.links = [];
}

Chord.prototype.setData = function(_dept,_depts){
	this.dept = JSON.parse(JSON.stringify(_dept));
	this.depts = JSON.parse(JSON.stringify(_depts));

	// zjl_debug 这边其实应该校验数据的
}

Chord.prototype.filter = function(startTime,endTime){
	var start = getTime(startTime),
		end = getTime(endTime),
		current,
		key;

	for(key in this.dept){
		current = getTime(key.split('__')[1]);
		if( current<start || current>end ){
			delete this.dept[key];
			//this.dept[key] = undefined;
		}
	}

	for( key in this.depts ){
		current = getTime( key.split('__')[1]);
		if( current<start || current>end ){
			delete this.depts[key];
		}
	}

}

Chord.prototype.genArcs = function(){
	var allArcs = count(this.dept),
		idx,sum=0;
	
	for(idx=ARC_SIZE;idx<allArcs.length;idx++){
		sum = sum+allArcs[idx].value;
	}
	this.arcs.push({
		key: DEFAULT_ID,
		value: sum
	});

	this.arcs = this.arcs.concat(allArcs.slice(0,ARC_SIZE-1));
	this.arcs.sort(sortByValue);
	
}


Chord.prototype.genNodes = function(){
	var all = count(this.depts),
		idx,sum=0;
	
	this.nodes = all.slice(0,NODE_SIZE-1);
	for(idx=NODE_SIZE;idx<all.length;idx++){
		sum = sum+all[idx].value;
	}
	this.nodes.push({
		key: DEFAULT_ID,
		value: sum
	});
	this.nodes.sort(sortByValue);
}

Chord.prototype.genLinks = function(){
	var key,
		list = count(this.depts),
		length = list.length,
		sourceIds = extractIds(this.arcs),
		targetIds = extractIds(this.nodes),
		source,
		target,
		ids,
		idx,
		idl,
		existed,
		entity;


	for( idl=0;idl<length;idl++ ){
		entity = list[idl];
		target = entity.key;
		ids = target.split(',');
		for( idx=0;idx<ids.length;idx++ ){
			source = ids[idx];
			source = contains(sourceIds,source)?source:DEFAULT_ID;
			target = contains(targetIds,target)?target:DEFAULT_ID; 
			if( source!==DEFAULT_ID && target!==DEFAULT_ID ){
				this.links.push({
					source: source,
					target: target,
					value: entity.value
				});
			} else {
				existed = getLink(this.links,source,target);
				if( existed ===undefined ){
					existed = {
						source: source,
						target: target,
						value: 0
					};
					this.links.push(existed);
				}
				existed.value = existed.value+entity.value;
			} 
		}	
	}
}

Chord.prototype.render = function(dim){
	var total,
		idx,
		length,
		entity,
		color = {},
		chart = {
			arcs: [],
			nodes: [],
			links: []
		};

	dim[DEFAULT_ID] = '其他';

	this.genArcs();
	this.genNodes();
	this.genLinks();


	total = sum(this.arcs);
	length = this.arcs.length;
	for(idx=0;idx<length;idx++){
		entity = this.arcs[idx];
		chart.arcs.push({
			total: total,
			Amount: entity.value,
			CMTE_ID: entity.key,
			CMTE_NM: dim[entity.key]
		});
	}	
	
	length = this.nodes.length;
	for(idx=0;idx<length;idx++){
		entity = this.nodes[idx];

		color[entity.key] = idx%2==0?'REP':'DEM';

		chart.nodes.push({
			total: total,
			// zjl_debug
			PTY: color[entity.key],
			Amount: entity.value,
			CAND_NAME: getLabel(dim,entity.key),
			CAND_ID: entity.key
		});
	}

	length = this.links.length;
	for(idx=0;idx<length;idx++){
		entity = this.links[idx];
		chart.links.push({
			total: total,
			PTY: color[entity.target],
			CAND_ID: entity.target,
			TRANSACTION_AMT: entity.value,
			CMTE_ID: entity.source
		});
	}
	return chart;
}

Chord.prototype.show = function(){
	var key;
	console.log( '========================');
	console.log('=====chord: ');
	for( key in this.dept ){
		if( this.dept[key] !==undefined ){
			console.log( key + '> '+ this.dept[key].join(','));
		}
	}

	console.log('=====arcs: ');
	for(key=0;key<this.arcs.length;key++){
		console.log( this.arcs[key].key +' > ' + this.arcs[key].value )
	}

	console.log('=====nodes: ');
	for(key=0;key<this.nodes.length;key++){
		console.log( this.nodes[key].key +' > ' + this.nodes[key].value )
	}
}
function getTime(time){
	var num = time.split('-'),
		date = new Date(),
		month = num[0],
		day = num[1],
		year = num[2];

	date.setDate(day);
	date.setMonth(month-1);
	date.setFullYear(year);

	return date.getTime();
}

function count(list){
	var group = {},
		result = [],
		key,
		newKey,
		entity;

	for( key in list ){
		entity = list[key];
		newKey = key.split('__')[0];
	//	newKey = newKey.split(',').sort(function(e1,e2){
	//		return e1-e2;
	//	}).join(',');

		if( group[newKey] ===undefined ){
			group[newKey] = [];
		}
		group[newKey] = group[newKey].concat(entity );
	}

	for( key in group ){
		result.push({
			key: key,
			value: group[key].length
		});
	}

	result.sort(function(entity1,entity2){
		return entity1.value-entity2.value;
	});
	result.reverse();

	return result;
}

function extractIds(list){
	var idx,result=[];
	for( idx=0;idx<list.length;idx++ ){
		result.push(list[idx].key);
	}
	return result;
}

function contains(list,entity){
	var idx;
	for(idx=0;idx<list.length;idx++){
		if( list[idx] === entity ){
			return true;
		}
	}
	return false;
}

function getLink(list,source,target){
	var idx,entity,
		length = list.length;
	for( idx=0;idx<length;idx++){
		if( list[idx].source === source && list[idx].target ===target ){
			return list[idx];
		}
	}
	return undefined;
}

function sum(list){
	var idx,
		sum = 0,
	   	length = list.length;
	for(idx=0;idx<length;idx++){
		sum = sum + list[idx].value;
	}
	return sum
}
	
function getLabel(dim,keys){
	var idx,array = keys.split(','),
		length = array.length,
		labels = [];
	for( idx=0;idx<length;idx++){
		labels.push(dim[array[idx]]);
	}
	return labels.join(',');
}

/**
 * 反序排序
 */
function sortByValue(e1,e2){
	return e2.value-e1.value;
}

module.exports = Chord;

